from i_home.utils.Compress_picture import compress_picture
import json, re
import logging
from django.contrib.auth import logout, login, authenticate
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from i_home.utils.view import LoginRequiredMixin
from users.models import User

logger = logging.getLogger('django')



# 上传头像
class UploadAvatarView(LoginRequiredMixin, View):
    def post(self, request):
        user = request.user
        img = request.FILES.get('avatar')
        if not img:
            return JsonResponse({'errno': 400, 'errmsg': '请先选择图片'})
        image_url, ret = compress_picture(img)
        try:
            user.avatar = image_url
            user.save()
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '上传失败'})
        dict = {}
        dict['avatar_url'] = image_url
        print(image_url)
        return JsonResponse({'data': dict, 'errno': '0',
                             'errmsg': '头像上传成功'})



# 用户中心

class UserinfoView(LoginRequiredMixin,View):
    # 用户中心
    def get(self, request):
        user = request.user
        data = {
            "avatar_url": str(user.avatar),
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id
        }
        return JsonResponse({'data': data, 'errmsg': 'ok', 'errno': '0'})

# 用户名修改
class UserSet(LoginRequiredMixin,View):

    def put(self,request):
        json_data = json.loads(request.body)
        name = json_data.get('name')

        if not name:
            return JsonResponse({'errno':4002,'errmsg':'无数据'})
        if not re.match('^[a-zA-Z0-9_]{4,16}$',name):
            return JsonResponse({'errno':4004,'errmsg':'用户名数据错误'})
        try:
            User.objects.filter(id=request.user.id).update(username=name)
        except Exception as e:
            return JsonResponse({'errno':4001,'errmsg':'数据库错误'})
        return JsonResponse({'errno':0,'errmsg':'修改成功'})




class UsersTure(LoginRequiredMixin,View):
    #实名认证
    def get(self,request):
        try:
            real_name =request.user.real_name
            id_card = request.user.id_card
        except Exception as e:

            return JsonResponse({'errno': 4002, 'errmsg': '请实名认证'})
        # 添加返回实名数据bug
        data_dict = {
            "real_name": real_name,
            "id_card" : id_card
        }

        return JsonResponse({'errno': 0, 'errmsg': '无数据', "data":data_dict})



    def post(self,request):

        json_data = json.loads(request.body)
        real_name = json_data.get('real_name')
        id_card = json_data.get('id_card')


        if not all([real_name,id_card]):
            return JsonResponse({'errno':4003,'errmsg':'缺少数据'})
        if not re.match(r'^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$',real_name):
            return JsonResponse({'errno':4004,'errmsg':'用户名数据错误'})
        if not re.match(r"^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", id_card):
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})


        try:
            user = User.objects.get(id=request.user.id)
            user.id_card = id_card
            user.real_name = real_name
            user.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '存储错误'})
        return JsonResponse({
            "errno": "0",
            "errmsg": "认证信息保存成功"
        })


        # if not all([real_name,id_card]):
        #     return JsonResponse({'errno':4003,'errmsg':'数据已存在'})
        # if not re.match(r'^[\u4e00-\u9fa5]+(·[\u4e00-\u9fa5]+)*$',real_name):
        #     return JsonResponse({'errno':4004,'errmsg':'用户名数据错误'})
        # if not re.match(r'^[1-9]\d{7}((0\d)|(1[0-2]))'
        #             r'(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}'
        #             r'((0\d)|(1[0-2])([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$', id_card):
        #     return JsonResponse({'errno':4004,'errmsg':'请输入正确身份证'})
        # # try:
        # #     User.objects.filter(id = request.id).update(real_name=real_name,id_card=id_card)
        # # except Exception as e:
        # #     logger.error(e)
        # #     return JsonResponse({'errno':4004,'errmsg':'数据错误'})
        # # return JsonResponse({'errno':0, 'errmsg': '认证信息保存成'})
        # try:
        #     user = User.objects.get(id = request.user.id)
        #     user.id_card=id_card
        #     user.real_name=real_name
        # except Exception as e:
        #     logger.error(e)
        #     return JsonResponse({'errno':4004,'errmsg':'数据错误'})
        # user.save()
        # return JsonResponse({'errno':0, 'errmsg': '认证信息保存成'})

# 用户注册
class RegisterView(View):

    def post(self, request):
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        phonecode_cient = dict.get('phonecode')
        password = dict.get('password')

        # 2.校验参数
        if not all([mobile, phonecode_cient, password]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })
        # 3.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })
        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })

        # 5.phonecode检验 (链接redis数据库)
        redis_conn = get_redis_connection('verify_code')

        # 6.从redis中取值
        phonecode_server = redis_conn.get('sms_%s' % mobile)

        # 7.判断该值是否存在
        if not phonecode_server:
            return JsonResponse({
                'errno': 4001,
                'errmsg': 'NODATA'
            })
        # 8.把redis中取得值和前端发的值对比
        if phonecode_cient != phonecode_server.decode():
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })

        # 9.保存到数据库 (password mobile)
        try:
            user = User.objects.create_user(username=mobile,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({
                'errno': 4004,
                'errmsg': 'DATAERR'
            })
        # 10.实现状态保持
        login(request, user)

        # 生成响应对象
        response = JsonResponse({'errno': 0,
                                 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('name',
                            user.mobile,
                            max_age=3600 * 24 * 14)

        # 返回响应结果
        return response


class LoginView(View):
    # 登录代码接口优化

    def get(self, request):
        dict = {}
        dict['name'] = request.user.username
        dict['user_id'] = request.user.id
        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': dict
        })

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        # 2.校验(整体 + 单个)
        if not all([mobile, password]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': 'PARAMERR'
            })

        # 3.验证是否能够登录
        user = authenticate(username=mobile,
                            password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({
                'errno': 4102,
                'errmsg': 'LOGINERR'
            })

        # 4.状态保持
        login(request, user)

        # 生成响应对象
        response = JsonResponse({'errno': 0,
                                 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('name',
                            user.mobile,
                            max_age=3600 * 24 * 14)

        # 返回响应结果
        return response

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({"errno": "0",
                                 "errmsg": "已登出"})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response
